/**
 * @brief Timer stuff implementation
 * @author Gilad Avidov
 *
 * uses 16bit timer and interrupt count to calculate time elapsed
 */
#include <mcs51reg.h>
#include <stdio.h>
#include "timer.h"

volatile unsigned long timer0_irq_cnt;

unsigned long timer0_get_time_elapsed()
{
    unsigned char th;
    unsigned char tl;
    unsigned short irq;
    unsigned long elapsed;

	TR0 = 0x0;      // turn timer/counter 0 off
	th = TH0;
    tl = TL0;
    irq = timer0_irq_cnt;
	TR0 = 0x1;      // turn timer/counter 0 on

     //(irq << 16) | (th << 8) | tl;
    elapsed = irq;
    elapsed <<= 8;
    elapsed |= th;
    elapsed <<= 8;
    elapsed |= tl;

    return elapsed / 12;
}

void timer0_stop()
{
	ET0 = 0x0;      // disable timer zero interrupt
	TR0 = 0x0;      // turn timer/counter 0 off
}

void timer0_run()
{
	TMOD = (TMOD & 0xF0) | 0x01; // timer 0 16bit counter
	ET0 = 1;      // enable timer zero interrupt
	TR0 = 1;      // turn timer/counter 0 ON
	EA  = 1;      // global interrupt enable
}

void timer0_reset()
{
    timer0_irq_cnt = 0;
    TH0 = TH0_VAL;  // high counter value
    TL0 = TL0_VAL;  // low counter value
}
